package com.jcark.utils

import android.text.Spanned

import android.text.InputFilter
import java.lang.Exception


/**
 * Description: <br>
 * @author King.Zi<br>
 * @date 2023/5/9<br>
 * Email: 78688689@qq.com
 */
class InputFilterMinMax(private var minValue: Int = Int.MIN_VALUE, private var maxValue: Int = Int.MAX_VALUE) :
    InputFilter {
    override fun filter(
        source: CharSequence,
        start: Int,
        end: Int,
        dest: Spanned,
        dstart: Int,
        dend: Int
    ): CharSequence? {
        try {
            //限制小数点位数
            /* if (source == "." && dest.toString().length == 0) {
                 return "0."
             }
             if (dest.toString().contains(".")) {
                 val index = dest.toString().indexOf(".")
                 val mlength = dest.toString().substring(index).length
                 if (mlength == 3) {
                     return ""
                 }
             }*/
            //限制大小
            val input = (dest.toString() + source.toString()).toInt()
            if (isInRange(minValue, maxValue, input)) return null
        } catch (ex: Exception) {
        }
        return ""
    }

    private fun isInRange(a: Int, b: Int, c: Int): Boolean {
        return if (b > a) c in a..b else c in b..a
    }
}